﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using BesAsm.Stormwater.HspfUtility.Properties;
using BesAsm.Stormwater.HspfResults;
using BesAsm.Stormwater.HspfCore;

namespace BesAsm.Stormwater.HspfUtility
{
  public partial class Form1 : Form
  {
    ArrayList _mruQueueL61, _mruQueueWh2;
    public LandSegmentsCollection _results;

    public Form1()
    {
      InitializeComponent();
      ConfigureMruLists();
      cmbExtractionPeriod.DataSource =
        Enum.GetValues(typeof(L61ResultsTimePeriod));
      cmbExtractionPeriod.SelectedItem = L61ResultsTimePeriod.Monthly;
    }

    private void ConfigureMruLists()
    {
      _mruQueueL61 = new ArrayList();
      if (Settings.Default.L61FileMru == null)
        Settings.Default.L61FileMru = new System.Collections.Specialized.StringCollection();
      foreach (string s in Settings.Default.L61FileMru)
      {
        if (!_mruQueueL61.Contains(s))
          _mruQueueL61.Add(s);
      }

      cmbL61File.DataSource = _mruQueueL61;
      cmbL61File.DataBind();

      _mruQueueWh2 = new ArrayList();
      if (Settings.Default.Wh2FileMru == null)
        Settings.Default.Wh2FileMru = new System.Collections.Specialized.StringCollection();
      foreach (string s in Settings.Default.Wh2FileMru)
      {
        if (!_mruQueueWh2.Contains(s))
          _mruQueueWh2.Add(s);
      }

      cmbWh2File.DataSource = _mruQueueWh2;
      cmbWh2File.DataBind();
    }

    private void cmbL61File_EditorButtonClick(object sender, Infragistics.Win.UltraWinEditors.EditorButtonEventArgs e)
    {
      this.openFileDialog1.DefaultExt = "L61";
      this.openFileDialog1.Filter = "L61 file|*.L61|All files|*.*";

      if (openFileDialog1.ShowDialog() != DialogResult.OK)
        return;

      string fileName = openFileDialog1.FileName;

      cmbL61File.Text = fileName;

      UpdateL61MruList(fileName);

    }

    private void cmbWh2File_EditorButtonClick(object sender, Infragistics.Win.UltraWinEditors.EditorButtonEventArgs e)
    {
      this.openFileDialog1.DefaultExt = "Wh2";
      this.openFileDialog1.Filter = "Wh2 file|*.wh2|All files|*.*";

      if (openFileDialog1.ShowDialog() != DialogResult.OK)
        return;

      string fileName = openFileDialog1.FileName;

      cmbWh2File.Text = fileName;

      UpdateWh2MruList(fileName);
    }

    private void UpdateL61MruList(string fileName)
    {
      while (_mruQueueL61.Count > 4)
        _mruQueueL61.RemoveAt(_mruQueueL61.Count - 1);

      cmbL61File.DataBindings.Clear();
      cmbL61File.DataSource = _mruQueueL61;
      cmbL61File.DataBind();

      _mruQueueL61.Insert(0, fileName);
    }

    private void UpdateWh2MruList(string fileName)
    {
      while (_mruQueueWh2.Count > 4)
        _mruQueueWh2.RemoveAt(_mruQueueL61.Count - 1);

      cmbWh2File.DataBindings.Clear();
      cmbWh2File.DataSource = _mruQueueWh2;
      cmbWh2File.DataBind();

      _mruQueueWh2.Insert(0, fileName);
    }

    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
      SaveMruLists();
    }

    private void SaveMruLists()
    {
      Settings.Default.L61FileMru.Clear();
      Settings.Default.L61FileMru.AddRange(_mruQueueL61.Cast<string>().Take(5).ToArray<string>());
      Settings.Default.Wh2FileMru.Clear();
      Settings.Default.Wh2FileMru.AddRange(_mruQueueWh2.Cast<string>().Take(5).ToArray<string>());
      Settings.Default.Save();
    }

    private void btnReadL61_Click(object sender, EventArgs e)
    {
      string fileName = cmbL61File.Text;
      L61Reader reader = ReadL61File(fileName);

      if (reader == null)
        return;

      bindingSourceSegments.DataSource = reader.LandSegments;
    }

    private L61Reader ReadL61File(string fileName)
    {
      if (!File.Exists(fileName))
      {
        MessageBox.Show("File does not exist");
        return null;
      }

      L61Reader reader = new L61Reader(fileName);
      L61ResultsTimePeriod resultsPeriod =
        (L61ResultsTimePeriod)cmbExtractionPeriod.SelectedItem;

      reader.Read(resultsPeriod);
      return reader;
    }

    private void btnExportAll_Click(object sender, EventArgs e)
    {



    }

    private void btnReadWh2File_Click(object sender, EventArgs e)
    {
      string fileName = cmbWh2File.Text;

      Wh2Reader reader = ReadWh2File(fileName);
      if (reader == null)
        return;

      bindingSourceWh2Contents.DataSource = reader.GetDataTable();
    }

    private Wh2Reader ReadWh2File(string fileName)
    {
      if (!File.Exists(fileName))
      {
        MessageBox.Show("File does not exist");
        return null;
      }

      Wh2Reader reader = new Wh2Reader(fileName);

      reader.Read();
      return reader;
    }

    private void btnCalcCatchmentFlows_Click(object sender, EventArgs e)
    {
      DataTable dt = new DataTable();

      Wh2Reader wh2reader = null;
      try
      {
        string wh2File = cmbWh2File.Text;
        wh2reader = ReadWh2File(wh2File);
      }
      catch (Exception ex)
      {
        return;
      }
      finally
      {
        if (wh2reader == null || !wh2reader.IsRead)
        {
          MessageBox.Show("Wh2 File not read");
        }
      }

      L61Reader l61reader = null;
      try
      {
        string l61File = cmbL61File.Text;
        l61reader = ReadL61File(l61File);
      }
      catch (Exception ex)
      {
        return;
      }
      finally
      {
        if (l61reader == null || !l61reader.IsRead)
        {
          MessageBox.Show("L61 File not read");
        }
      }

      List<CatchmentResultsCollection> allCatchmentResults;

      ResultsCombiner combiner = new ResultsCombiner();
      allCatchmentResults = combiner.MergeReaders(wh2reader, l61reader);

      bindingSourceCatchments.DataSource = allCatchmentResults;

      return;

    }

    private void bindingSourceSegments_CurrentChanged(object sender, EventArgs e)
    {
      BindingSource bs = (BindingSource)sender;
      LandSegmentResults ls = (LandSegmentResults)bs.Current;

      DataTable dt = ls.GetDataTable();
      bindingSourceSegmentResults.DataSource = dt;

      grdLandSegmentResults.DisplayLayout.Bands[0].Columns[0].Format = "MMMM yyyy";
    }

    private void bindingSourceCatchments_CurrentChanged(object sender, EventArgs e)
    {
      BindingSource bs = (BindingSource)sender;
      CatchmentResultsCollection crc = (CatchmentResultsCollection)bs.Current;

      grdCatchmentResults.DataSource = crc;
    }

    private void btnExportSelectedSegment_Click(object sender, EventArgs e)
    {
      LandSegmentResults ls = null;

      try
      {
        ls = (LandSegmentResults)bindingSourceSegments.Current;

        saveFileDialog1.FileName
          = ls.Name
          .Replace(' ', '_')
          .Replace(",", "")
          .Replace('\\', '_')
          .Replace('/', '_') + ".csv";
      }
      catch (Exception ex)
      {
        MessageBox.Show(
          "Please select a Land Segment to export",
          "No Land Segment Selected",
          MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        return;
      }

      if (saveFileDialog1.ShowDialog() != DialogResult.OK)
        return;

      string file = saveFileDialog1.FileName;

      ls.WriteResults(file);
    }

    private void btnExportAllSegments_Click(object sender, EventArgs e)
    {
      MessageBox.Show("Not implemented");
    }

    private void btnExportSelectedCatchment_Click(object sender, EventArgs e)
    {
      CatchmentResultsCollection crc = null;
      try
      {
        crc = (CatchmentResultsCollection)bindingSourceCatchments.Current;

        saveFileDialog1.FileName
          = crc.Name
          .Replace(' ', '_')
          .Replace(",", "")
          .Replace('\\', '_')
          .Replace('/', '_') + "_results.csv";
      }
      catch (Exception ex)
      {
        MessageBox.Show(
          "Please select a Catchment Result to export",
          "No Catchment Result Selected",
          MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        return;
      }

      if (saveFileDialog1.ShowDialog() != DialogResult.OK)
        return;

      string file = saveFileDialog1.FileName;

      crc.WriteResults(file);
    }

    private void btnExportAllCatchments_Click(object sender, EventArgs e)
    {
      MessageBox.Show("Not implemented");
    }

    private void btnExporBasinTotals_Click(object sender, EventArgs e)
    {
      string fileName = string.Empty;
      try
      {
        fileName = Path.GetFileNameWithoutExtension(cmbL61File.Text) + "_basin_results.csv";

        saveFileDialog1.FileName
          = fileName
          .Replace(' ', '_')
          .Replace(",", "")
          .Replace('\\', '_')
          .Replace('/', '_');
      }
      catch (Exception ex)
      {
        MessageBox.Show(
          "Unable to save catchments totals",
          "Catchment Totals Not Exported",
          MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        return;
      }

      if (saveFileDialog1.ShowDialog() != DialogResult.OK)
        return;

      fileName = saveFileDialog1.FileName;

      CatchmentResultsCollection total = new CatchmentResultsCollection(new Catchment("Basin"));

      List<CatchmentResultsCollection> crcList =
        (List<CatchmentResultsCollection>)bindingSourceCatchments.DataSource;

      if (crcList == null || crcList.Count == 0)
      {
        MessageBox.Show("No catchment results loaded");
        return;
      }

      foreach (CatchmentResultsCollection crc in crcList)
      {
        total.Area += crc.Area;
        foreach (CatchmentResult cr in crc)
        {
          total.AccumulateResult(cr);
        }

      }

      total.WriteResults(fileName);
    }

  }

}
